#include <signal.h>
#include <sys/wait.h>
#include "msgQueue.h"
#include "tools.h"
#include "bank.h"

//消息队列ID
int stocMsgId = 0;
int ctosMsgId = 0;

//用于存储子进程ID
pid_t subPid[9] = {};

void sigint(int signum)
{
	//杀死所有子进程
	for(int i=0;i<9;i++)
	{
		printf("正在杀死子进程%d\n",subPid[i]);
		kill(subPid[i],SIGINT);
		usleep(100000);
	}

	//删除两个消息队列
	deleteMsg(stocMsgId);
	deleteMsg(ctosMsgId);

	//父进程自杀
	exit(EXIT_SUCCESS);
}

int main()
{
	//监控Ctrl+c
	signal(SIGINT,sigint);

	//初始化银行卡号
	initCardNo(BANK_PATH,132400000);

	//获取两个消息队列
	stocMsgId = getMsg(STOC_KEY);
	ctosMsgId = getMsg(CTOS_KEY);

	//子进程存在的路径
	char* path[] = {"bin/open","bin/login","bin/destroy","bin/unlock","bin/save","bin/take","bin/query","bin/transfer","bin/resetPassword"};

	//加载子进程
	for(int i=0;i<9;i++)
	{
		subPid[i] = vfork();
		if(0 == subPid[i])
		{
			execl(path[i],"server",NULL);
		}

		printf("创建子进程:%u,%s\n",subPid[i],path[i]);
		usleep(100000);
	}

	//等待子进程结束，防止他们变成孤儿
	while(-1 != wait(NULL));
}
